<?php

include_once 'ZReader.php';
include_once 'ZAuthorCollection.php';
include_once 'ZAuthorItem.php';

class ZAuthorReader extends ZReader {
    /**
     * Generate command string
     * @return string
     */
    public function command() {
        return sprintf('authors %s %s %s %s %s %s %s'."\r\n",
            $this->session,
            $this->begin,
            $this->end,
            $this->timeZone,
            $this->languages,
            $this->types,
            $this->query
        );
    }

    /**
     * Parse data that receive from server to object
     * @param $callback
     * @param $state
     * @return void|ZAuthorCollection
     */
    public function parse($callback, &$state) {
        $i          = 0;
        $arr        = array();
        $succeed    = false;
        $count      = 0;
        $collection = new ZAuthorCollection();

        //Read data while not end of file
        while (!$this->eof()) {
            //Read the first block is the length of the data
            $numBytes = $this->readNum();

            if ($numBytes >= 0 && $numBytes < 0xffffffff) {
                //Read data
                if ($i == 2) {
                    $arr[] = $this->readNum($numBytes);
                }
                else {
                    $arr[] = $this->readStr($numBytes);
                }

                $i++;

                //Enough a item
                if ($i == 3) {
                    $item   = new ZAuthorItem($arr[0], $arr[1], $arr[2]);
                    $arr    = array();
                    $i      = 0;

                    if (is_callable($callback)) {
                        $callback($item);
                    }

                    $collection->addItem($item);

                    $count++;
                }
                //Not succeeded
                $succeed = false;
            }
            else if ($numBytes == 0xffffffff) {
                $succeed = true;
            }
        }

        $state = $succeed ? ($count > 0 ? 1 : 0) : -1;

        return $collection;
    }

    /**
     * Read author data
     * @param null  $callback   callback function when receive data
     * @return ZAuthorCollection
     * @throws Exception
     */
    public function read($callback = null) {
        return parent::readData($callback);
    }
}

?>
